package com.js.study.datastructs.stack;

/**
 * @Author JiangSen
 * @DATE 2023/12/26 10:47
 */
public class MyStack<E> implements IStackDesc<E>{
    E[] data;
    int size;
    public MyStack(){
        this(5);
    }
    public MyStack(int capacity){
        if(capacity <= 0){
            throw new IllegalArgumentException("init param is illegal");
        }
        this.data = (E[]) new Object[capacity];
        this.size = 0;
    }

    @Override
    public void push(E e) {
        if(isFull()){
            throw new IllegalArgumentException("full");
        }
        data[size] =e;
        size++;
    }

    @Override
    public E pop() {
        if(isEmpty()){
            throw new IllegalArgumentException("stack is empty");
        }
        E result = data[size -1];
        size--;
        data[size] = null;
        return result;
    }

    @Override
    public E peek() {
        return data[size-1];//查看当前栈顶
    }

    @Override
    public int getSize() {
        return size;
    }

    @Override
    public boolean isFull() {
        return size == data.length;
    }

    @Override
    public boolean isEmpty() {
        return size == 0;
    }

    @Override
    public void print() {
        for(int i =0; i< size; i++){
            System.out.println(data[i]);
        }
    }

    public static void main(String[] args) {
        MyStack<Integer> myStack = new MyStack<>();

        for (int i = 0; i < 5; i++) {
            myStack.push(i + 1);
        }
        myStack.print();
        System.out.println();

        System.out.println(myStack.pop());
        System.out.println(myStack.peek());
        myStack.print();
    }
}


